package Agents.Sensor;

import AOP.Printer;
import Agents.Messageable;
import Messages.AMessage;
import Messages.EmitMessage;
import Messages.MeasureMessage;
import Messages.NotUnderstoodMessage;
import jade.core.Agent;
import jade.core.behaviours.*;
import jade.lang.acl.ACLMessage;

@SuppressWarnings("serial")
public class World extends ASensor
{
	//Environment variables
	private int temperature = 60; //in fahrenheit: 60 F = 15 C --> 80 F = 27 C
	private int noise = 57; //in dB
	private int light;
	private int noiseCounter = 0;
	
	protected void setup()
	{
		addBehaviour(new TickerBehaviour(this, AMessage.unitsManipulatingConstant * 10)//60) //Diminish environment variables behavior
		{
			protected void onTick()
			{
				temperature = temperature - 1;

				Printer.Print(myAgent.getLocalName(), temperature);
				//System.out.println("World " + myAgent.getLocalName() + ": Recieved heat change from: Wind. Temperature is now: " + temperature); //TODO
			}
		});
		
		addBehaviour(new TickerBehaviour(this, AMessage.unitsManipulatingConstant)
					     //CyclicBehaviour(this)
		{
			//public void action() 
			public void onTick()
			{

				ACLMessage  msg = myAgent.receive();
				if(msg != null)
				{
					String content = msg.getContent();
					AMessage am = null;
  					try
  					{
  						am = AMessage.retrieveMessage(content);
  					}
  					catch(Exception e)
  					{
  						Printer.error(msg);
  					}
					
					if(msg.getPerformative()== ACLMessage.INFORM)
					{

						if(AMessage.GlobalNames.decode(am.getSender()) == AMessage.GlobalNames.FLOOR_HEATER_AGENT)
						{
							temperature = temperature + ((EmitMessage)am).value;

							Printer.Print(myAgent.getLocalName(), temperature);
							//System.out.println("World " + myAgent.getLocalName() + ": Recieved heat change from: " + am.getSender() + ". Temperature is now: " + temperature); //TODO
						}
					}
					else if(msg.getPerformative()== ACLMessage.REQUEST)
					{
						ACLMessage reply = msg.createReply();

						if(AMessage.GlobalNames.decode(am.getSender()) == AMessage.GlobalNames.TEMPERATURE_SENSOR_AGENT)
						{
							reply.setPerformative(ACLMessage.INFORM);
							((ASensor)myAgent).unit = AMessage.Units.TEMPERATURE;
							((ASensor)myAgent).value = temperature;
							reply.setContent(AMessage.constructMessage((Messageable)myAgent, AMessage.MessageType.MEASUREMENT));
						}
						else 
						{
							reply.setPerformative(ACLMessage.NOT_UNDERSTOOD);
							//System.out.println("( (Unexpected-act "+ACLMessage.getPerformative(msg.getPerformative())+") )"); //TODO
							reply.setContent(NotUnderstoodMessage.constructSpecialMessage((Messageable)myAgent, am));   
						}
						send(reply);
					}
				}
			}
		});
	}

	@Override
	public void getMeasuredValue() 
	{ 	}
}
